function getMouse(event)
{
	var canvas=document.getElementById("box");
    var ctx=canvas.getContext("2d");
	event=event||window.event;
    var rect = canvas.getBoundingClientRect();
    x=event.clientX-rect.left*(canvas.width/rect.width);
    y=event.clientY-rect.top*(canvas.height/rect.height);
    newton(x,y);
}

var CZ=new Array();
var X=new Array();
var Y=new Array();
var y_list=new Array();
function newton(x,y)
{
	X.splice(X.length,0,x);
	Y.splice(Y.length,0,y);
	if (CZ.length>0)
	{
		var len=CZ[(CZ.length-1)].length+1;
		CZ[CZ.length]=new Array(len);
		CZ[(CZ.length-1)][0]=x;
		CZ[(CZ.length-1)][1]=y;
		for (var i=2;i<len;i++)
		{
			CZ[(CZ.length-1)][i]=(CZ[(CZ.length-1)][i-1]-CZ[(CZ.length-2)][i-1])/(CZ[(CZ.length-1)][0]-CZ[(CZ.length-i)][0]);
		}
		y_list.splice(y_list.length,0,CZ[(CZ.length-1)][len-1])
	}
	else
	{
		CZ[CZ.length]=new Array(2);
		CZ[(CZ.length-1)][0]=x;
		CZ[(CZ.length-1)][1]=y;
		y_list.splice(-1,0,y);
	}

	ansys()
}

function ansys()
{
	var c=document.getElementById("box");  
    var ctx=c.getContext("2d");  
    c.height=c.height; 
	for (var x=X[0];x<=X[X.length-1];x++)
	{
		sum=0;
		for (var y=0;y<y_list.length;y++)
		{
			w=1;
			if (y>0)
			{
				for (var z=0;z<y;z++)
				{
					w*=(x-X[z]);
				}
			}
			sum+=w*y_list[y];
		}
		if (x==X[0])
		{
			ctx.moveTo(x,sum);
		}
		else
		{
			ctx.lineTo(x,sum);
		}
	}
	ctx.lineWidth=5;
	ctx.strokeStyle="#000"; 
	ctx.stroke();
	for (var m=0;m<X.length;m++)
	{
		circle(X[m],Y[m],"red");
	}
}

function circle(x,y,color)
{
	var canvas=document.getElementById("box");
    var ctx=canvas.getContext("2d");
    ctx.beginPath();
	ctx.arc(x,y,10,0,2*Math.PI);
	ctx.fillStyle=color;
	ctx.fill();
}

function refresh()
{
	var c=document.getElementById("box");  
    var ctx=c.getContext("2d");  
    c.height=c.height;
    X=new Array();
    Y=new Array();
    y_list=new Array();
    CZ=new Array();
}